//
//  ViewController.swift
//  UIDynamic
//
//  Created by 杜承玖 on 2/27/15.
//  Copyright (c) 2015 redianying. All rights reserved.
//

import UIKit

class ViewController: UIViewController, UICollisionBehaviorDelegate {

    var animator = UIDynamicAnimator()
    var gravity = UIGravityBehavior()
    var collision = UICollisionBehavior()
    var firstContact = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let square = UIView(frame: CGRectMake(100, 100, 100, 100))
        square.backgroundColor = UIColor.grayColor()
        view.addSubview(square)
        
        animator = UIDynamicAnimator(referenceView: view)
        gravity = UIGravityBehavior(items: [square])
        animator.addBehavior(gravity)
        
        let barrier = UIView(frame: CGRectMake(0, 300, 130, 20))
        barrier.backgroundColor = UIColor.redColor()
        view.addSubview(barrier)
        
        collision = UICollisionBehavior(items: [square])
        collision.translatesReferenceBoundsIntoBoundary = true
        animator.addBehavior(collision)
        
        //添加一个碰撞体
        let rightEdge = CGPointMake(barrier.frame.origin.x + barrier.frame.size.width, barrier.frame.origin.y)
        collision.addBoundaryWithIdentifier("barrier", fromPoint: barrier.frame.origin, toPoint: rightEdge)
        
        collision.action = {
            println("(NSStringFromCGAffineTransform(square.transform)),(NSStringFromCGPoint(square.center))") //只要动就会触发，可以获得动的物体的位置
        }
        collision.collisionDelegate = self
        
        let itemBehaviour = UIDynamicItemBehavior(items: [square])
        itemBehaviour.elasticity = 0.6 //更改弹性
        animator.addBehavior(itemBehaviour)
    }
    
    func collisionBehavior(behavior: UICollisionBehavior, beganContactForItem item: UIDynamicItem, withBoundaryIdentifier identifier: NSCopying, atPoint p: CGPoint) {
        println("began contact") //碰撞时触发
        //每次碰撞都会变黄一下，然后又转成灰色
        let view = item as UIView
        view.backgroundColor = UIColor.yellowColor()
        UIView.animateWithDuration(0.3, animations: {
            view.backgroundColor = UIColor.grayColor()
        })
        
        //检测第一次碰撞，动态添加behaviors
        if !firstContact {
            firstContact = true
            //处理第一次碰撞的地方
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

